package com.chen.guolimail.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.common.utils.PageUtils;
import com.chen.common.utils.Query;

import com.chen.guolimail.product.dao.CategoryDao;
import com.chen.guolimail.product.entity.CategoryEntity;
import com.chen.guolimail.product.service.CategoryService;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryDao categoryDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils listWithTree() {
        List<CategoryEntity> entities = categoryDao.selectList(null);
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0)
                .peek((menu) -> menu.setChildren(getChildren(menu, entities)))
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort()))
                .collect(Collectors.toList());
        return new PageUtils(level1Menus, 1);
    }

    private List<CategoryEntity> getChildren(CategoryEntity category, List<CategoryEntity> entities){
        return entities.stream()
                .filter(category1 -> category1.getParentCid().equals(category.getCatId()))
                .peek(category1 -> category1.setChildren(getChildren(category1, entities)))
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort()))
                .collect(Collectors.toList());
    }
}